package com.ahcloud.enhance.redisson.lock;

import com.ahcloud.enhance.lock.base.ILock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

/**
 * @program: distributedlock-enhance
 * @description:
 * @author: YuKai Fan
 * @create: 2024/4/30 22:47
 **/
public class RedissonILock implements ILock<RedissonClient> {

    private final RedissonClient client;

    public RedissonILock(RedissonClient client) {
        this.client = client;
    }

    @Override
    public void lock(String lockKey) throws Exception {
        RLock lock = getClient().getLock(lockKey);
        lock.lock();
    }

    @Override
    public void unlock(String lockKey) throws Exception {
        RLock lock = getClient().getLock(lockKey);
        lock.unlock();
    }

    @Override
    public void lock(String lockKey, int timeout) throws Exception {
        throw new UnsupportedOperationException("redisson lock not support operation");
    }

    @Override
    public void lock(String lockKey, long timeout, TimeUnit unit) throws Exception {
        throw new UnsupportedOperationException("redisson lock not support operation");
    }

    @Override
    public boolean tryLock(String lockKey) throws Exception {
        RLock lock = getClient().getLock(lockKey);
        return lock.tryLock();
    }

    @Override
    public boolean tryLock(String lockKey, long waitTime, TimeUnit unit) throws Exception {
        RLock lock = getClient().getLock(lockKey);
        return lock.tryLock(waitTime, unit);
    }

    @Override
    public boolean tryLock(String lockKey, long waitTime, long leaseTime, TimeUnit unit) throws Exception {
        RLock lock = getClient().getLock(lockKey);
        return lock.tryLock(waitTime, leaseTime, unit);
    }

    @Override
    public boolean isLocked(String lockKey) {
        RLock lock = getClient().getLock(lockKey);
        return lock.isLocked();
    }

    @Override
    public RedissonClient getClient() {
        return client;
    }
}
